package com.summerbird.mallchat.transaction.aspect;

import cn.hutool.core.date.DateUtil;
import com.summerbird.mallchat.transaction.annotation.SecureInvoke;
import com.summerbird.mallchat.transaction.domain.dto.SecureInvokeDTO;
import com.summerbird.mallchat.transaction.domain.entity.SecureInvokeRecord;
import com.summerbird.mallchat.transaction.service.SecureInvokeHolder;
import com.summerbird.mallchat.transaction.service.SecureInvokeService;
import com.summerbird.mallchat.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE + 1)//确保最先执行
@Component
public class SecureInvokeAspect {
    @Autowired
    private SecureInvokeService secureInvokeService;

    @Around("@annotation(secureInvoke)")
    public Object around(ProceedingJoinPoint joinPoint, SecureInvoke secureInvoke) throws Throwable {
        boolean async = secureInvoke.async();;
        boolean inTransaction = TransactionSynchronizationManager.isActualTransactionActive();
        // 1. 非事务状态，则直接执行，不保存到本地消息表中
        // 2. 消息环绕通知，在同步方法中，会先后调用两次该方法
        if(SecureInvokeHolder.IS_INVOKING() || !inTransaction){
            return joinPoint.proceed();
        }
        // 构造本地消息对象
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        List<String> parameters = Stream.of(method.getParameterTypes()).map(Class::getName).collect(Collectors.toList());
        SecureInvokeDTO secureInvokeDTO = SecureInvokeDTO.builder()
                        .className(method.getDeclaringClass().getName())
                        .args(JsonUtils.toStr(joinPoint.getArgs()))
                        .parameterTypes(JsonUtils.toStr(parameters))
                        .methodName(method.getName())
                        .build();
        SecureInvokeRecord record = SecureInvokeRecord.builder()
                .secureInvokeDTO(secureInvokeDTO)
                .maxRetryTimes(secureInvoke.maxRetryTimes())
                .nextRetryTime(DateUtil.offsetMinute(new Date(), (int) SecureInvokeService.RETRY_INTERVAL_MINUTES))
                .build();
        secureInvokeService.invoke(record, async);
        return null;
    }

}
